#include "E2PROM.h"
#include "I2C.h"
#include "Com_Util.h"

#define EEPROM_ADDRESS_WRITE 0xA0
#define EEPROM_ADDRESS_READ 0xA1

void Hardware_EEPROM_Init(void)
{
    Hardware_IIC_Init();
}

void Hardware_EEPROM_PageWriteBytes(uint8_t address, uint8_t *bytes, uint8_t size)
{
    Hardware_IIC_Start();
    Hardware_IIC_SendAddress(EEPROM_ADDRESS_WRITE);
    
    Hardware_IIC_SendByte(address);

    for (uint8_t i = 0; i < size; i++)
    {
        Hardware_IIC_SendByte(bytes[i]);
    }
    Hardware_IIC_Stop();

    Delay_ms(5);
}

void Hardware_EEPROM_WriteBytes(uint8_t address, uint8_t *bytes, uint8_t size)
{
    uint8_t page_size = 16 - address % 16;
    if (page_size >= size)
    {
        Hardware_EEPROM_PageWriteBytes(address, bytes, size);
    } else {
        Hardware_EEPROM_PageWriteBytes(address, bytes, page_size);
        Hardware_EEPROM_WriteBytes(address + page_size, bytes + page_size, size - page_size);
    }
    
}

void Hardware_EEPROM_ReadBytes(uint8_t address, uint8_t *bytes, uint8_t size)
{
    Hardware_IIC_Start();
    Hardware_IIC_SendAddress(EEPROM_ADDRESS_WRITE);

    Hardware_IIC_SendByte(address);

    Hardware_IIC_Start();
    Hardware_IIC_SendAddress(EEPROM_ADDRESS_READ);
    
    for (uint8_t i = 0; i < size; i++)
    {
        if (i == size - 1)
        {
            Hardware_IIC_SendNACK();
        } else {
            Hardware_IIC_SendACK();
        }
        
        bytes[i] = Hardware_IIC_ReceiveByte();
    }

    Hardware_IIC_Stop();
}
